package com.wasion.gydpe.ice;

public class IceWrapper {
	protected Ice.Communicator _comm; // 通讯器
	protected Ice.ObjectAdapter _adapter; // 适配器

	public IceWrapper(Ice.Communicator comm, String adapterName,
			String portNames) {
		_comm = comm;
		_adapter = _comm.createObjectAdapterWithEndpoints(adapterName,
				portNames);
		_adapter.activate();
	}

	public Ice.ObjectPrx createProxy(String name) {
		return createProxy(name, false);
	}

	public Ice.ObjectPrx createProxy(String name, boolean isProperty) {

		return (isProperty ? _comm.propertyToProxy(name).ice_twoway() : _comm
				.stringToProxy(name).ice_twoway());
	}

	public Ice.ObjectAdapter getAdapter() {
		return _adapter;
	}

	public Ice.Communicator getCommunicator() {
		return _comm;
	}

	public String getPropertyWithDefault(String sKey, String value) {
		return _comm.getProperties().getPropertyWithDefault(sKey, value);
	}

	public void addProxyWithNotify(String name, String prxInit,
			ICommExpNotify notify, short state) {
		Ice.ObjectPrx prx = createProxy(prxInit);
		addProxyWithNotify(name, prx, notify, state);
	}

	public void addProxyWithNotify(String name, Ice.ObjectPrx prx,
			ICommExpNotify notify, short state) {
		CHeartbeatMonitor.getInstance().attach(name, prx, notify, state);
	}

	public Ice.ObjectPrx getPublishProxy(String topic) {
		// 取得主题管理代理
		IceStorm.TopicManagerPrx manager = IceStorm.TopicManagerPrxHelper
				.checkedCast(_comm.propertyToProxy("TopicManager.Proxy"));

		if (null == manager) {
			return null; // 返回空代理
		}

		// 取得主题，没有则创建
		IceStorm.TopicPrx topicPrx;
		try {
			topicPrx = manager.retrieve(topic);
		} catch (IceStorm.NoSuchTopic ex1) {
			try {
				topicPrx = manager.create(topic);
			} catch (IceStorm.TopicExists ex2) {
				return null;
			}
		}

		return topicPrx.getPublisher(); // 返回主题的发布代理
	}
}
